

<template>
  <!-- 面包屑 -->
  <div>
    <el-breadcrumb :separator-icon="ArrowRight">
      <el-breadcrumb-item>首页</el-breadcrumb-item>
      <el-breadcrumb-item>日常管理</el-breadcrumb-item>
      <el-breadcrumb-item>伙食管理</el-breadcrumb-item>
      <el-breadcrumb-item><b>菜品配置</b></el-breadcrumb-item>
    </el-breadcrumb>
  </div>
  <!-- 搜索框 -->
  <div style="margin:40px 20px 20px 20px">
    <el-form :inline="true" ref="searchFormRef" :model="searchFormModel" class="demo-form-inline" style="margin-top: 20px">
      <el-form-item label="菜品名称：" prop="dishName">
        <el-input v-model="searchFormModel.dishName" placeholder="请输入菜品名称" clearable style="width:140px" />
      </el-form-item>
      <el-form-item label="类别：" prop="dishType"  >
        <el-select
            v-model="searchFormModel.dishType"
            placeholder="请选择..."
            clearable
            style="width:120px"
        >
          <el-option label="早餐" value="早餐"></el-option>
          <el-option label="午餐" value="午餐"></el-option>
          <el-option label="晚餐" value="晚餐"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="searchOnSubmit">
          <el-icon><Search /></el-icon>  查询
        </el-button>
        <el-button type="danger"   @click="deleteSelectedRows()">
          <el-icon><Delete /></el-icon> 批量删除
        </el-button>
      </el-form-item>
    </el-form>
  </div>
  <div>
    <el-button type="success" @click="dialogAddState=true">
      <el-icon><Plus /></el-icon>  添加
    </el-button>
  </div>
  <!--  表格-->
  <div style="margin:20px">
    <el-table :data="dishInfo" stripe border style="width: 100%"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="序号" v-if="false"/>
      <el-table-column prop="dishType" label="类别"/>
      <el-table-column prop="numLimit" label="数量限制"/>
      <el-table-column prop="dishName" label="菜品名称"  />
      <el-table-column prop="price" label="原价"  />
      <el-table-column prop="discountPrice" label="优惠价" />
<!--    显示图片  -->
      <el-table-column prop="photourl" label="图片" >
        <template #default="scope">
          <el-image style="width: 50px;height: 50px;border-radius: 5px"
          :src="scope.row.photourl"
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column prop="assignDt" label="分配" />
      <el-table-column prop="note" label="备注" />
      <el-table-column label="操作" width="160">
        <template #default="scope">
          <el-button
              size="small"
              type="primary"
              @click="tableEditHandler(scope.$index, scope.row)">
            <el-icon><Edit /></el-icon>编辑
          </el-button>
          <el-button
              size="small"
              type="danger"
              @click="tableDeleteHandler(scope.$index, scope.row)">
            <el-icon><Delete /></el-icon>删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <!--  分页-->
  <div class="page">
    <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5,8]"
        :small="small"
        :disabled="disabled"
        :background="background"
        layout="sizes, prev, pager, next"
        :total="totals"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </div>

  <!--新增  -->
  <el-dialog v-model="dialogAddState" title="添加菜品" width="480">
    <div>
      <el-form ref="formAddRef"  :model="formAdd"
               :rules="dishRules"
               label-width="120px">
        <el-form-item prop="dishName" label="菜品名称">
          <el-input v-model="formAdd.dishName"></el-input>
        </el-form-item>
        <el-form-item prop="dishType" label="类别">
          <el-select v-model="formAdd.dishType">
            <el-option label="早餐" value="早餐"></el-option>
            <el-option label="午餐" value="午餐"></el-option>
            <el-option label="晚餐" value="晚餐"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="numLimit" label="数量限制">
          <el-input-number v-model="formAdd.numLimit" :min="1" :max="15" />
        </el-form-item>
        <el-form-item prop="price" label="原价">
          <el-input v-model="formAdd.price" ></el-input>
        </el-form-item>
        <el-form-item prop="discountPrice" label="优惠价">
          <el-input v-model="formAdd.discountPrice" ></el-input>
        </el-form-item>
        <el-form-item prop="photourl" label="图片">
<!--    上传图片     -->
          <el-upload
            :action="'http://localhost:9094/upload'"
            :on-success="handleFiledUpload"
            list-type="picture">
            <el-button type="primary">上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item prop="note" label="备注">
          <el-input v-model="formAdd.note" ></el-input>
        </el-form-item>
        <el-form-item prop="assignDt" label="分配">
            <el-select v-model="formAdd.assignDt" multiple placeholder="请选择..." >
              <el-option label="星期一" value="星期一"></el-option>
              <el-option label="星期二" value="星期二"></el-option>
              <el-option label="星期三" value="星期三"></el-option>
              <el-option label="星期四" value="星期四"></el-option>
              <el-option label="星期五" value="星期五"></el-option>
            </el-select>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogAddOnReset">取消</el-button>
        <el-button type="primary"  @click="dialogAddOnSubmit" >确认</el-button>
      </div>
    </template>
  </el-dialog>

  <!--  修改-->
  <el-dialog v-model="dialogEditState" title="修改菜品" width="380">
    <div>
      <el-form ref="formEditRef" :model="formEdit"
               :rules="editRules"
               label-width="120px">
        <el-form-item prop="id" v-if="false">
          <el-input v-model="formEdit.id" ></el-input>
        </el-form-item>
        <el-form-item prop="discountPrice" label="优惠价">
          <el-input v-model="formEdit.discountPrice" ></el-input>
        </el-form-item>
        <el-form-item prop="numLimit" label="数量限制">
          <el-input v-model="formEdit.numLimit" ></el-input>
        </el-form-item>
        <el-form-item prop="note" label="备注">
          <el-input v-model="formEdit.note" ></el-input>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogEditOnReset">取消</el-button>
        <el-button type="primary"  @click="dialogEditOnSubmit" >确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>

import {ArrowRight, Delete, Edit, Plus, Search} from "@element-plus/icons-vue";
import {onMounted, reactive, ref} from "vue";
import request from "../../../utils/daily";
import {ElMessage, ElMessageBox} from "element-plus";
import axios from "axios";
onMounted(()=>{
  getDish();
})
//分页
const currentPage = ref(1)
const pageSize = ref(5)
const small = ref(false)
const background = ref(false)
const disabled = ref(false)
let totals=ref(0);
const dishInfo=ref([]);
//搜索框
const searchFormRef=ref();
const searchFormModel=reactive({
  dishName:'',
  dishType:''
})
const  getDish=()=>{
  const params = {
    pageNum: currentPage.value,
    pageSize: pageSize.value,
    // 初始时不包含其他参数
  };
  if (searchFormModel.dishName && searchFormModel.dishName.trim() !== ''){
    params.dishName=searchFormModel.dishName.trim();
  }
  if (searchFormModel.dishType && searchFormModel.dishType.trim() !== ''){
    params.dishType=searchFormModel.dishType.trim();
  }
  request({
    url:'/dish/getDish',
    method:'get',
    params,
  }).then((req)=>{
    if (200==req.data.errorCode){
      dishInfo.value=req.data.data.records;
      totals.value=req.data.data.total;
    }
  })
}
const searchOnSubmit=()=>{
  getDish();
}
const handleSizeChange = (val) => {
  pageSize.value=val;
  getDish();
}
const handleCurrentChange = (val) => {
  currentPage.value=val;
  getDish();
}

//删除一条
const tableDeleteHandler = (rowIndex , rowData) => {
  ElMessageBox.confirm(
      '确认删除 : ' +rowData.id,
      'Warning',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(() => {//点击了删除按钮
    request({
      method:'delete',
      url:'/dish/deleteDish/'+rowData.id
    }).then(req=>{
      if (200==req.data.errorCode){
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
        getDish();
      }
    })
  })
      .catch(() => {//点击了取消按钮
        ElMessage({
          type: 'info',
          message: '取消删除',
        })
      })
}
//删除多个
const selectedRows=ref([])
const handleSelectionChange=(rows)=>{
  selectedRows.value = rows;
}
const deleteSelectedRows=()=>{
  if (selectedRows.value.length == 0) {
    ElMessage({
      message: '请选择要删除菜品所在行：',
      type: 'warning',
    });
    return;
  }

  ElMessageBox.confirm(
      '此操作将永久删除选中的日志, 是否继续?',
      'Warning',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        // 获取所有选中的日志ID
        const ids = selectedRows.value.map(row => row.id).join(',');
        request({
          method: 'delete',
          url: '/dish/deletes',
          params:{id:ids}
        }).then((response) => {
          console.log(response)
          if (response.data.errorCode == 200) {
            ElMessage({
              type: 'success',
              message: '批量删除成功',
            });
            getDish(); // 刷新菜品列表
          }
        }).catch(() => {
          ElMessage({
            type: 'error',
            message: '批量删除失败',
          });
        });
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '已取消删除',
        });
      });
};
//////添加表单校验
const dishRules = {
  dishName: [
    { required: true, message: '请输入菜品名称', trigger: 'blur' },
    { validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error('请输入菜品名称'));
        } else if (!/^[\u4e00-\u9fa5]+$/.test(value)) {
          callback(new Error('菜品名称只能包含汉字'));
        } else {
          callback();
        }
      }, trigger: 'blur' }
  ],
  dishType: [
    { required: true, message: '请输入菜品类别', trigger: 'blur' }
  ],
  numLimit: [
    { required: true, message: '请输入最大售卖份数', trigger: 'blur' }
  ],
  price: [
    { required: true, message: '请输入菜品原价', trigger: 'blur' }
  ],
  assignDt: [
    { required: true, message: '请输入售卖日期', trigger: 'blur' }
  ],
}
//添加
const dialogAddState = ref(false)
const formAddRef = ref()
const formAddData = {
  dishName:'',
  dishType:'',
  numLimit:'',
  note:'',
  price:'',
  discountPrice:'',
  assignDt:[],
  photourl:''
}

// 新增表单绑定数据模型
const formAdd = reactive({...formAddData})   // ...formAddData 解构formAddData
const handleFiledUpload=(res)=>{
  console.log("图片:"+res)
 if (res != null){
   formAdd.photourl=res
 }else {
   formAdd.photourl=""
 }
}
const dialogAddOnSubmit = () => {

  //校验
  /*formAddRef.value.validate((valid)=>{
    if (valid){
      //表单校验通过，提交逻辑
    }
  })*/
  formAddRef.value.validate((valid)=>{
    if (valid){
      //表单校验通过，提交逻辑
      //数组转字符串
      formAdd.assignDt = formAdd.assignDt.join(',');
      request({
        method:'post',
        url:'/dish/addDish',
        data:formAdd,
      }).then(req=>{
        if (200 == req.data.errorCode){
          ElMessage({
            type:'success',
            message:req.data.msg
          })
          Object.assign(formAdd , formAddData)
          formAdd.photourl=""
          getDish();
        }
      })
      dialogAddState.value=false;
    }
  })
//////
}
const dialogAddOnReset = () => {
  // 清空表单数据
  Object.assign(formAdd , formAddData)
  // 关闭对话框
  dialogAddState.value = false
}
//编辑
const formEditRef = ref()
const formEditData = {
  id:'',
  discountPrice:'',
  numLimit:'',
  note:''
}
// 编辑表单绑定数据模型
const formEdit = reactive({...formEditData})
const tableEditHandler = (rowIndex , rowData) => {
  console.log("-------------")
  console.log(rowIndex)
  console.log(rowData)
  formEdit.id=rowData.id
  formEdit.discountPrice = rowData.discountPrice
  formEdit.numLimit = rowData.numLimit
  formEdit.note = rowData.note
  dialogEditState.value = true
}
const dialogEditState = ref(false)

//编辑表单 校验
const editRules={
  numLimit: [
    { required: true, message: '请输入最大售卖份数', trigger: 'blur' }
  ]
}
const dialogEditOnSubmit = () => {
  formEditRef.value.validate((valid)=>{
    if (valid){
      //表单校验通过，处理提交逻辑
      request({
        url: '/dish/updateDish',
        method: 'put',
        data: JSON.stringify(formEdit),
        headers: {'content-type': "application/json;charset=UTF-8"}
      }).then(response => {
        if (response.data.errorCode == 200) {
          ElMessage({
            type: 'success',
            message: '修改成功！',
          });
          dialogEditState.value = false
          getDish();
        } else {
          ElMessage({
            type: 'error',
            message: '修改失败！',
          });
        }
      })
    }
  })
}
const dialogEditOnReset = () => {
  Object.assign(formEdit , formEditData)
  dialogEditState.value = false
}

</script>
<style scoped>
.el-breadcrumb{
  font-size: 18px;
  margin: 20px;
}
.page{
  margin-left: 30%;
}
</style>